package com.example.front.serivce;

import com.example.common.dto.ListDto;
import com.example.common.dto.Pagination;
import com.example.common.exception.BusinessException;
import com.example.front.dto.BoxCreateDto;
import com.example.front.dto.BoxDto;
import com.example.front.entity.Box;
import com.example.front.entity.Department;
import com.example.front.entity.Equipment;
import com.example.front.mapper.DepartmentMapper;
import com.example.interceptor.UserContext;
import com.example.passport.dto.WxUserDto;
import com.example.passport.entity.User;
import com.example.passport.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

@Service
public class DepartmentService {

    @Resource
    DepartmentMapper departmentMapper;
    @Resource
    UserMapper userMapper;

    public ListDto<Department> list(Department condition, Pagination pagination){
        long total = departmentMapper.count(condition);
        if (total == 0) {
            return new ListDto<>(new ArrayList<>(), pagination);
        }
        pagination.setTotal(total);
        List<Department> list = departmentMapper.list(condition, pagination);
        return new ListDto(list, pagination);
    }


    public Department find(@Valid Department department) {
        User me = UserContext.getUser();
        return departmentMapper.find(department);
    }

    /**
     * 跟新数据
     */
    public void update(@Valid Department department) {
        User me = UserContext.getUser();
        department.setTenantId(me.getTenantId());
        if (departmentMapper.update(department) < 1) {
            throw new BusinessException("操作失败");
        }
    }

    /**
     * 删除
     */
    public void deleteById(long id) {
        List<User> byIdDepId = userMapper.findByIdDepId(id);

        if (byIdDepId.size() > 0){
            throw new BusinessException("当前部门下已有员工,请先删除或者修改其部门");
        }
        if (departmentMapper.delete(id) < 1) {
            throw new BusinessException("操作失败");
        }
    }

    /**
     * 创建
     */
    @Transactional
    public void create(@Valid Department condition) {
        Department department = departmentMapper.find(condition);
        if (department != null){
            throw new BusinessException("部门名称重复");
        }
        departmentMapper.create(condition);
    }

}
